package ca.bcit.comp_3512.assignment_02.business_logic;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;

import ca.bcit.comp_3512.assignment_02.data_managers.UserManager;
import ca.bcit.comp_3512.assignment_02.data_models.User;

@Named("editableUserList")
@SessionScoped
public class EditableUserList implements Serializable
{
    @Inject private UserManager userManager;
    List<EditableUser> userList;
    
    public List<EditableUser> getUserList()
    {
        if (userList == null) {
            refreshList();
        }
        return userList;
    }
    
    public void refreshList()
    {
        User[] users = userManager.getAll();
        userList = new ArrayList<EditableUser>();
        for (int i = 0; i < users.length; ++i)
        {
            userList.add(new EditableUser(users[i]));
        }  
    }
    
    public  void setUserList(List<EditableUser> users)
    {
        userList = users;
    }

    public String deleteRow(EditableUser user)
    {
        userManager.remove(user.getUser());
        userList.remove(user);
        return null;
    }
    
    public String saveAll()
    {
        for (EditableUser user : userList)
        {
            if (user.isEditable())
            {
                userManager.merge(user.getUser());
                user.setEditable(false);
            }
        }
        return null;
    }
     
    public String save(EditableUser user)
    {
        userManager.merge(user.getUser());
        user.setEditable(false);
        return null;
    }
    
    public String edit(EditableUser user)
    {
        user.setEditable(!user.isEditable());
        return "admin?faces-redirect=true";
    }
}
